import mongoose, { Schema, model } from "mongoose";
import type Typings from "../typings";
import { createDb } from "../mongoose/mongoose";
const db = createDb("auth", "user");

// 定义 Schema 模型
const UserSchema = new Schema<Typings.User.instance>({
  id: {
    type: String,
    required: true,
    unique: true,
  },

  account: {
    // type: Schema.Typings.Mixed, // 表示接受任何类型的数据
    type: String,
    required: true,
    unique: true,
    validate: {
      validator: function (v: string) {
        return /^[a-z]{4,10}$/.test(v);
      },
      message: "账号仅支持字母，且长度保持在4 ~ 10",
    },
  },

  password: {
    type: String,
    required: true,
    validate: {
      validator: function (v: string) {
        return /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{0,10}$/.test(v);
      },
      message: "密码必须含有数字和字母，且长度保持在10以内",
    },
  },

  name: {
    type: String,
    required: true,
    validate: {
      validator: function (v: string) {
        return /^[\u4e00-\u9fa5]{1,6}$/.test(v);
      },
      message: "名称必须为中文，且保持在6个字符以内",
    },
  },

  gender: {
    type: String,
    required: true,
    validate: {
      validator: function (v: string) {
        return ["1", "2"].includes(v);
      },
      message: "gender 数值格式不正确",
    },
  },

  roleId: {
    type: String,
    required: true,
  },

  avatar: {
    type: String,
    default: "",
  },

  desc: {
    type: String,
    default: "暂无描述",
  },

  createdTime: {
    type: Number,
    Number,
    required: true,
    default: Date.now(),
  },

  updatedTime: {
    type: Number,
    required: true,
    default: Date.now(),
  },

  creatorId: {
    type: String,
    required: true,
    default: "",
  },
});

// 排除 _id 和 __v 字段
UserSchema.set("toObject", {
  virtuals: true,
  versionKey: false,
  transform: (doc, ret: any) => {
    delete ret._id;
    delete ret.__v;
  },
});

UserSchema.set("toJSON", {
  virtuals: true,
  versionKey: false,
  transform: (doc, ret: any) => {
    delete ret._id;
    delete ret.__v;
  },
});

const UserModel = db.model<Typings.User.instance>("User", UserSchema, "users");

export default UserModel;
